<template>
    <div class="home">
        <div class="content-layout">
            <main class="home-main-content">
                <Carousel
                    v-if="carouselSlides?.length > 0"
                    :slides="carouselSlides"
                    @click="goToPost"
                />
                <MomentsList />
                <div>
                    <el-tabs v-model="activeName" @tab-click="handleClick">
                        <el-tab-pane
                        v-for="category in categories"
                        :key="category.id"
                        :name="String(category.id)"
                        >
                        <template #label>
                            <span class="label-info">
                            <!-- <i :class="category.icon"></i> -->
                            <el-icon>
                                <component :is="category.icon" />
                            </el-icon>
                            {{ category.name }}
                            </span>
                        </template>
                        <ArticleList
                            :articles="articleList"
                            :loading="loading"
                            :total="total"
                            :params="params"
                            @article-click="goToPost"
                            @page-change="changePage"
                            class="article-list"
                        />
                        </el-tab-pane>
                    </el-tabs>
                </div>
            </main>
            <Sidebar />
        </div>
    </div>
</template>

<script setup>
import { ref, markRaw, onMounted } from 'vue'
import ArticleList from "@/components/ArticleList/index.vue";
import Carousel from '@/views/Home/components/carousel.vue';
import MomentsList from "@/views/Home/components/moments.vue";
import Sidebar from "@/components/Sidebar/index.vue";
import { Menu,Document,Collection,Reading,CoffeeCup,Notebook,Edit  } from '@element-plus/icons-vue';
import {
  getArticlesApi,
  getCarouselArticlesApi,
  getAllCategoriesApi,
} from "@/api/article";
import  { useRouter } from 'vue-router';
const router = useRouter();
const carouselSlides = ref([])
const activeName = ref("all")
const categories = ref([
    {
        id: "all",
        name: "全部",
        icon: markRaw(Menu),
    }
])
const params = ref({
    pageNum: 1,
    pageSize: 10,
})
const loading = ref(false)
const articleList = ref([])
const total = ref(0)
 /**
 * 切换标签
 * @param {string} tab 标签 
 * @param {Event} event 事件
 */
 const handleClick = (tab,e)=> {
    console.log("tabclick",tab.name,e)
    params.value.categoryId = e.name === "all" ? null : e.name;
    params.value.pageNum = 1;
    getArticleList();
};
/**
 * 跳转到文章详情
 * @param {number} id 文章id
 */
const goToPost = (id) => {
  // 在 setup 中使用路由需要导入 useRouter
  router.push(`/post/${id}`);
};
/**
 * 切换页码
 * @param {number} page 页码
 */
const changePage = (page) => {
  params.value.pageNum = page;
  getArticleList();
  const postsSection = document.querySelector('.posts-section');
  if (postsSection) {
    window.scrollTo({
      top: postsSection.offsetTop - 80,
      behavior: "smooth",
    });
  }
};
/**
 * 获取文章列表
 */
const getArticleList = async () => {
  loading.value = true;
  try {
    const res = await getArticlesApi(params.value);
    articleList.value = res.data.records;
    total.value = res.data.total;
  } catch (error) {
    console.error("Failed to fetch articles:", error);
  } finally {
    loading.value = false;
  }
};
// 获取轮播和推荐文章
const getCarouselArticles = async () => {
  try {
    const res = await getCarouselArticlesApi();
    carouselSlides.value = res.data;
  } catch (error) {
    console.error("Failed to fetch carousel articles:", error);
  }
};
// 获取所有分类
const getAllCategories = async () => {
  try {
    const res = await getAllCategoriesApi();
    const icons = [
      Document,
      Collection,
      Reading,
      CoffeeCup,
      Notebook,
      Edit,
    ];
    const categoriesWithIcons = res.data.map((category) => ({
      ...category,
      icon: icons[Math.floor(Math.random() * icons.length)],
    }));
    categories.value.push(...categoriesWithIcons);
  } catch (error) {
    console.error("Failed to fetch categories:", error);
  }
};

// 组件挂载时调用获取数据的方法
onMounted(() => {
  getArticleList();
  getCarouselArticles();
  getAllCategories();
});
</script>

<style lang="scss" scoped>
.home{
    max-width: 1400px;
    margin: 0 auto;
    width: 100%;
    padding: $spacing-lg;

    @include responsive(lg){
        padding: $spacing-sm;
    }
}

.content-layout{
  display: grid;
  grid-template-columns: minmax(0,1fr) 320px;
  gap: $spacing-lg * 2;
  padding: 0 $spacing-xl;
  margin-bottom: $spacing-xl *2;
  min-height: calc(100vh - 80px);
  align-items: start;
  @include responsive(lg){
    grid-template-columns: 1fr;
    padding: $spacing-sm;
  }
}


.home-main-content {
  min-width: 0;
  width: 100%;
  height: 100%;

  .carousel {
    margin-bottom: $spacing-xl;
    width: 100%;
    max-height: 480px;

    @include responsive(md) {
      margin-bottom: $spacing-xl;
      max-height: 280px;
      :deep(h3) {
        font-size: 1.2em;
      }
    }
  }
}

:deep(.el-tabs__nav-scroll) {
  overflow-x: scroll !important;

  &::-webkit-scrollbar {
    display: none !important;
  }
}
:deep(.el-tabs__nav-wrap::after) {
  display: none;
}
.label-info {
  display: flex;
  align-items: center;
  gap: $spacing-base;
  color: var(--text-primary);
  // .el-icon{
  //   margin-right: 4px;
  //   vertical-align: middle;
  // }
}
</style>